import React, { useState, useEffect } from "react";
import Box from "./Box";
import Text from "./Text";
import Button from "./Button";
import { addMagicPoints } from "./UserMagic";

// 定义本地存储键名常量
const ONBOARDING_COMPLETED_KEY = "onboardingCompleted";
const ONBOARDING_REWARD_CLAIMED_KEY = "onboardingRewardClaimed";

// 高亮文本组件
const Highlight = ({ children }) => (
  <span
    style={{
      background:
        "linear-gradient(180deg, transparent 50%, rgba(51, 51, 51, 0.1) 50%)",
      padding: "0 4px",
      borderRadius: "3px",
      fontWeight: 500,
    }}
  >
    {children}
  </span>
);

// 简单图标显示
const Icon = ({ type }) => {
  const getIcon = () => {
    switch (type) {
      case "award":
        return "🏆";
      case "download":
        return "⬇️";
      case "upload":
        return "⬆️";
      case "search":
        return "🔍";
      case "comment":
        return "💬";
      case "star":
        return "⭐";
      case "warning":
        return "⚠️";
      case "event":
        return "📅";
      case "check":
        return "✅";
      case "next":
        return "➡️";
      case "prev":
        return "⬅️";
      case "close":
        return "✖️";
      default:
        return "📌";
    }
  };
  return <span style={{ fontSize: "24px" }}>{getIcon()}</span>;
};

const OnboardingGuide = ({ isFirstLogin, onClose }) => {
  const [currentStep, setCurrentStep] = useState(0);
  // 添加状态来跟踪是否已领取奖励
  const [rewardAlreadyClaimed, setRewardAlreadyClaimed] = useState(false);
  
  // 组件挂载时检查是否已领取奖励
  useEffect(() => {
    const rewardClaimed = localStorage.getItem(ONBOARDING_REWARD_CLAIMED_KEY) === "true";
    setRewardAlreadyClaimed(rewardClaimed);
  }, []);

  // 引导步骤内容
  const steps = [
    // 欢迎页
    {
      title: "欢迎来到我们的社区",
      icon: "award",
      content: (
        <Box>
          <Text mb={3}>
            欢迎加入我们的PT资源分享社区！接下来将为您介绍站点的基本规则和功能，帮助您快速融入社区。
          </Text>
          <Text mb={3}>完成本指南后，您将获得以下奖励：</Text>
          <Box
            display="flex"
            alignItems="center"
            bg="sidebar"
            p={3}
            borderRadius={2}
            mb={2}
          >
            <Icon type="award" />
            <Text ml={2}>初始上传量 5GB</Text>
          </Box>
          <Box
            display="flex"
            alignItems="center"
            bg="sidebar"
            p={3}
            borderRadius={2}
            mb={2}
          >
            <Icon type="award" />
            <Text ml={2}>新手福利种子包（免费下载）</Text>
          </Box>
          <Box
            display="flex"
            alignItems="center"
            bg="sidebar"
            p={3}
            borderRadius={2}
          >
            <Icon type="award" />
            <Text ml={2}>论坛新手勋章</Text>
          </Box>
        </Box>
      ),
    },
    // 分享率规则
    {
      title: "分享率与下载规则",
      icon: "download",
      content: (
        <Box>
          <Text mb={3}>
            在我们的社区中，<strong>分享率（Ratio）</strong>
            是最重要的指标之一。它是您的上传量与下载量的比值。
          </Text>
          <Text mb={3}>
            <strong>基本规则：</strong>
          </Text>
          <Text as="ul" mb={3} pl={3} style={{ listStyleType: "none" }}>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              分享率低于<Highlight>0.4</Highlight>将被警告
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              分享率低于<Highlight>0.2</Highlight>将无法下载新资源
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              新用户有<Highlight>1000GB</Highlight>的"魔力值"缓冲期
            </li>
          </Text>
          <Text mb={3}>
            <strong>提高分享率的方法：</strong>
          </Text>
          <Text as="ul" pl={3} style={{ listStyleType: "none" }}>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              长期做种，保持资源可用性
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              上传稀有或优质资源
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              参与论坛活动获取额外上传量
            </li>
            <li style={{ position: "relative", paddingLeft: "20px" }}>
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              邀请新用户加入可获得奖励
            </li>
          </Text>
        </Box>
      ),
    },
    // 上传规则
    {
      title: "上传与发布指南",
      icon: "upload",
      content: (
        <Box>
          <Text mb={3}>
            上传优质资源是社区发展的基础，我们鼓励用户分享独特的内容。
          </Text>
          <Text mb={3}>
            <strong>上传要求：</strong>
          </Text>
          <Text as="ul" mb={3} pl={3} style={{ listStyleType: "none" }}>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              禁止上传已有的重复资源
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              资源必须有清晰的分类和标签
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              资源描述需包含基本信息和截图
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              首次上传需审核，通过后可直接发布
            </li>
          </Text>
          <Text mb={3}>
            <strong>上传奖励：</strong>
          </Text>
          <Text as="ul" pl={3} style={{ listStyleType: "none" }}>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              每个原创资源奖励<Highlight>2GB</Highlight>上传量
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              高质量资源可获得管理员额外奖励
            </li>
            <li style={{ position: "relative", paddingLeft: "20px" }}>
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              首次上传资源获得<Highlight>"分享者"</Highlight>勋章
            </li>
          </Text>
        </Box>
      ),
    },
    // 魔力值系统
    {
      title: "魔力值系统",
      icon: "star",
      content: (
        <Box>
          <Text mb={3}>
            魔力值是站点的<strong>虚拟货币系统</strong>
            ，可通过多种方式获取和使用。
          </Text>
          <Text mb={3}>
            <strong>获取魔力值：</strong>
          </Text>
          <Text as="ul" mb={3} pl={3} style={{ listStyleType: "none" }}>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              每日签到：<Highlight>1-5点</Highlight>魔力值
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              做种：每小时获得做种魔力值
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              发布资源：每个资源<Highlight>10-50点</Highlight>
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              论坛活跃：发帖回复获得魔力值
            </li>
          </Text>
          <Text mb={3}>
            <strong>魔力值用途：</strong>
          </Text>
          <Text as="ul" pl={3} style={{ listStyleType: "none" }}>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              兑换上传量：<Highlight>100魔力值=1GB</Highlight>
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              购买邀请码：<Highlight>500魔力值/个</Highlight>
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              购买VIP资格：每月<Highlight>2000魔力值</Highlight>
            </li>
            <li style={{ position: "relative", paddingLeft: "20px" }}>
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              魔力值商店：购买各种站点特权
            </li>
          </Text>
        </Box>
      ),
    },
    // Hit&Run规则
    {
      title: "Hit&Run规则",
      icon: "warning",
      content: (
        <Box>
          <Text mb={3}>
            <Highlight>Hit&Run</Highlight>（下载后不做种）是站点
            <strong>禁止</strong>的行为，会影响您的账号状态。
          </Text>
          <Text mb={3}>
            <strong>H&R判定条件：</strong>
          </Text>
          <Text as="ul" mb={3} pl={3} style={{ listStyleType: "none" }}>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              下载完成后，未达到以下任一条件：
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "30px",
                marginBottom: "8px",
              }}
            >
              - 做种时间少于<Highlight>72小时</Highlight>
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "30px",
                marginBottom: "8px",
              }}
            >
              - 做种分享率小于<Highlight>1.0</Highlight>
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "30px",
                marginBottom: "8px",
              }}
            >
              - 未做种时间超过<Highlight>7天</Highlight>
            </li>
          </Text>
          <Text mb={3}>
            <strong>H&R惩罚：</strong>
          </Text>
          <Text as="ul" mb={3} pl={3} style={{ listStyleType: "none" }}>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              每次H&R记<Highlight>1次</Highlight>警告
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              <Highlight>3次</Highlight>警告限制下载权限24小时
            </li>
            <li
              style={{
                position: "relative",
                paddingLeft: "20px",
                marginBottom: "8px",
              }}
            >
              <span style={{ position: "absolute", left: "0", color: "#333" }}>
                •
              </span>
              累计<Highlight>10次</Highlight>警告账号将被禁用
            </li>
          </Text>
          <Text>
            小提示：如果您的网络条件不允许长期做种，可以通过魔力值消除H&R记录（每次
            <Highlight>200魔力值</Highlight>）。
          </Text>
        </Box>
      ),
    },
    // 完成页
    {
      title: "新手指南完成",
      icon: "check",
      content: (
        <Box>
          <Text mb={3}>
            恭喜您完成了新手指南！您现在已经了解了站点的基本规则和奖励机制。
          </Text>
          <Text mb={3}>
            <strong>您已获得以下奖励：</strong>
          </Text>
          <Box
            display="flex"
            alignItems="center"
            bg="sidebar"
            p={3}
            borderRadius={2}
            mb={2}
          >
            <Icon type="award" />
            <Text ml={2}>初始上传量 5GB 已添加到您的账户</Text>
          </Box>
          <Box
            display="flex"
            alignItems="center"
            bg="sidebar"
            p={3}
            borderRadius={2}
            mb={2}
          >
            <Icon type="award" />
            <Text ml={2}>新手福利种子包已解锁</Text>
          </Box>
          <Box
            display="flex"
            alignItems="center"
            bg="sidebar"
            p={3}
            borderRadius={2}
            mb={2}
          >
            <Icon type="award" />
            <Text ml={2}>论坛新手勋章已发放</Text>
          </Box>
          <Box
            display="flex"
            alignItems="center"
            bg="sidebar"
            p={3}
            borderRadius={2}
            mb={4}
            color="primary"
          >
            <Icon type="star" />
            <Text ml={2} fontWeight="bold">500魔力值已添加到您的账户</Text>
          </Box>
          <Text>
            现在您可以开始探索站点，下载资源，或者上传您的第一个种子。如有任何问题，可以查阅站点的帮助文档或在论坛中提问。
          </Text>
        </Box>
      ),
    },
  ];

  const handleNext = () => {
    if (currentStep < steps.length - 1) {
      setCurrentStep(currentStep + 1);
    } else {
      // 完成引导
      handleComplete();
    }
  };

  const handlePrev = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleComplete = () => {
    // 保存用户已完成引导的记录
    localStorage.setItem(ONBOARDING_COMPLETED_KEY, "true");

    // 只有在之前未领取过奖励的情况下才发放
    if (!rewardAlreadyClaimed) {
      // 添加500魔力值奖励
      addMagicPoints(500, "完成新手引导奖励");
      
      // 记录已领取奖励
      localStorage.setItem(ONBOARDING_REWARD_CLAIMED_KEY, "true");
    }

    // 关闭引导
    onClose();
  };

  const handleSkip = () => {
    // 提示用户将错过奖励
    if (!rewardAlreadyClaimed) {
      if (confirm("跳过新手引导将无法获得奖励，确定要跳过吗？")) {
        localStorage.setItem(ONBOARDING_COMPLETED_KEY, "true");
        onClose();
      }
    } else {
      // 已领取过奖励，直接关闭
      localStorage.setItem(ONBOARDING_COMPLETED_KEY, "true");
      onClose();
    }
  };

  // 修改最后一个步骤的内容，根据是否已领取奖励显示不同内容
  const getLastStepContent = () => {
    if (rewardAlreadyClaimed) {
      return (
        <Box>
          <Text mb={3}>
            您已经完成过新手指南并领取过奖励。感谢您再次查看新手指南！
          </Text>
          <Text>
            如有任何问题，可以查阅站点的帮助文档或在论坛中提问。
          </Text>
        </Box>
      );
    } else {
      return (
        <Box>
          <Text mb={3}>
            恭喜您完成了新手指南！您现在已经了解了站点的基本规则和奖励机制。
          </Text>
          <Text mb={3}>
            <strong>您已获得以下奖励：</strong>
          </Text>
          <Box
            display="flex"
            alignItems="center"
            bg="sidebar"
            p={3}
            borderRadius={2}
            mb={2}
          >
            <Icon type="award" />
            <Text ml={2}>初始上传量 5GB 已添加到您的账户</Text>
          </Box>
          <Box
            display="flex"
            alignItems="center"
            bg="sidebar"
            p={3}
            borderRadius={2}
            mb={2}
          >
            <Icon type="award" />
            <Text ml={2}>新手福利种子包已解锁</Text>
          </Box>
          <Box
            display="flex"
            alignItems="center"
            bg="sidebar"
            p={3}
            borderRadius={2}
            mb={2}
          >
            <Icon type="award" />
            <Text ml={2}>论坛新手勋章已发放</Text>
          </Box>
          <Box
            display="flex"
            alignItems="center"
            bg="sidebar"
            p={3}
            borderRadius={2}
            mb={4}
            color="primary"
          >
            <Icon type="star" />
            <Text ml={2} fontWeight="bold">500魔力值已添加到您的账户</Text>
          </Box>
          <Text>
            现在您可以开始探索站点，下载资源，或者上传您的第一个种子。如有任何问题，可以查阅站点的帮助文档或在论坛中提问。
          </Text>
        </Box>
      );
    }
  };

  // 更新步骤的内容
  const updatedSteps = [...steps];
  if (updatedSteps.length > 0) {
    updatedSteps[updatedSteps.length - 1] = {
      ...updatedSteps[updatedSteps.length - 1],
      content: getLastStepContent()
    };
  }

  // 使用内联样式创建弹窗
  return (
    <div
      style={{
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: "rgba(0, 0, 0, 0.7)",
        zIndex: 9999,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <div
        style={{
          backgroundColor: "white",
          padding: "30px",
          borderRadius: "12px",
          maxWidth: "700px",
          width: "90%",
          maxHeight: "85vh",
          overflow: "auto",
          boxShadow: "0 10px 30px rgba(0, 0, 0, 0.2)",
          position: "relative",
        }}
      >
        {/* 关闭按钮 */}
        <button
          onClick={handleSkip}
          style={{
            position: "absolute",
            top: "15px",
            right: "15px",
            background: "none",
            border: "none",
            cursor: "pointer",
            fontSize: "24px",
          }}
        >
          <Icon type="close" />
        </button>

        {/* 标题区域 */}
        <Box textAlign="center" mb={4}>
          <div
            style={{
              width: "70px",
              height: "70px",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              backgroundColor: "#f8f8f8",
              borderRadius: "50%",
              margin: "0 auto 20px",
              fontSize: "32px",
            }}
          >
            <Icon type={updatedSteps[currentStep].icon} />
          </div>
          <Text as="h2" fontSize={4} mb={2} fontWeight="bold" color="primary">
            {updatedSteps[currentStep].title}
          </Text>
        </Box>

        {/* 进度条 */}
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            padding: "0 20px",
            margin: "0 auto 25px",
            maxWidth: "400px",
          }}
        >
          {updatedSteps.map((_, index) => (
            <div
              key={index}
              style={{
                width: "10px",
                height: "10px",
                borderRadius: "50%",
                backgroundColor: index <= currentStep ? "#333" : "#e0e0e0",
                position: "relative",
              }}
            />
          ))}
        </div>

        {/* 内容区域 */}
        <div style={{ minHeight: "300px", marginBottom: "20px" }}>
          {updatedSteps[currentStep].content}
        </div>

        {/* 按钮区域 */}
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            marginTop: "20px",
            paddingTop: "20px",
            borderTop: "1px solid #eee",
          }}
        >
          {currentStep > 0 ? (
            <Button onClick={handlePrev} variant="outline">
              上一步
            </Button>
          ) : (
            <Button onClick={handleSkip} variant="outline">
              跳过
            </Button>
          )}

          <Button onClick={handleNext}>
            {currentStep < updatedSteps.length - 1 ? (
              <>
                下一步
              </>
            ) : (
              "完成"
            )}
          </Button>
        </div>
      </div>
    </div>
  );
};

export default OnboardingGuide;
